package com.ham.ui;

import java.util.List;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import com.ham.dto.MenuItemDTO;

//import com.vox.banking.desktop.ui.context.SecurityContext;

/**
 * 
 * @author fredy
 */
public class TreeMenuRenderer {

	private JTree tree;
	private List<MenuItemDTO> menuItems;
	private String rootTitle;

	public static class MenuItemModel {

		private MenuItemDTO menu;

		public MenuItemDTO getMenu() {
			return menu;
		}

		public MenuItemModel(MenuItemDTO menu) {
			this.menu = menu;
		}

		@Override
		public String toString() {
			return String.format("%s - %s", menu.getCode(), menu.getTitle());
		}
	}

	public TreeMenuRenderer(JTree tree, List<MenuItemDTO> menuItems,
			String rootTitle) {
		this.tree = tree;
		this.menuItems = menuItems;
		this.rootTitle = rootTitle;
	}

	public void render() {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootTitle);
		DefaultTreeModel treeModel = new DefaultTreeModel(root);
		buildTree(root, menuItems);
		tree.setModel(treeModel);
	}

	private boolean buildTree(DefaultMutableTreeNode parentNode,
			List<MenuItemDTO> menus) {
		boolean authorized = false;
		for (MenuItemDTO childMenu : menus) {
			// boolean nodeAuthorized = SecurityContext.getInstance()
			// .getUserInfo().isAuthorize(childMenu.getCode());
			boolean nodeAuthorized = true;
			DefaultMutableTreeNode node = new DefaultMutableTreeNode(
					new MenuItemModel((childMenu)));
			if (nodeAuthorized || buildTree(node, childMenu.getChildren())) {
				parentNode.add(node);
				authorized = true;
			}
		}
		return authorized;
	}
}
